<template>
  <div class="mainDiv">
    <el-container class="main_container">
      <el-main>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-card>
          <div slot="header" class="clearfix">
            <span>数据筛选</span>
          </div>
          <el-row>
            <el-col :span="5">
              <el-form-item label="仓库" prop="storeId">
                <el-select v-model="form.storeId" placeholder="仓库" clearable size="small">
                  <el-option v-for="dict in storeOptions" :key="dict.id" :label="dict.label"
                    :value="dict.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" v-if="form.storeId">
              <el-form-item label="库区" prop="areaId">
                <el-select v-model="form.areaId" placeholder="请选择库区" clearable size="small" >
                  <el-option v-for="item in storeAreaOptions" :key="item.id" :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" v-if="(ano == 'ZX'||ano == 'DX')?false:true && form.areaId">
              <el-form-item label="货柜" prop="cabinetGroupId">
                <el-select v-model="form.cabinetGroupId" placeholder="请选择货柜" clearable size="small" >
                  <el-option v-for="item in cabinetGroupOptions" :key="item.id" :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" v-if="(ano == 'CL'||ano == 'ZX'||ano == 'DX')?false:true && form.cabinetGroupId">
              <el-form-item label="货架" prop="cabinetId">
                <el-select v-model="form.cabinetId" placeholder="请选择货架" clearable size="small" >
                  <el-option v-for="item in cabinetOptions" :key="item.id" :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" v-if="ano == 'PT' && form.cabinetGroupId">
              <el-form-item label="层数" prop="floors">
                <el-select v-model="form.floors" placeholder="请选择层数" clearable size="small">
                  <el-option v-for="item in floorsOptions" :key="item.value" :label="item.name"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="地域" prop="region">
                <el-select v-model="form.regions" placeholder="地域" clearable multiple size="small">
                  <el-option v-for="dict in dict.type.wms_put_task_area" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="物品类型" prop="inventoryType">
                <el-select v-model="form.inventoryType" placeholder="物品类型" clearable size="small">
                  <el-option v-for="dict in inventoryTypeOptions" :key="dict.id" :label="dict.label"
                             :value="dict.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="入库时间" prop="inTime">
                <el-date-picker v-model="form.inTime" size="small" style="width: 240px" format="yyyy-MM-dd HH" value-format="yyyy-MM-dd HH"
                                type="datetimerange" range-separator="-" start-placeholder="创建起始日期" end-placeholder="截止日期"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="格口" prop="locatorIds">
                <el-select v-model="form.locatorIds" placeholder="请选择格口" clearable size="small" multiple style="min-width: 80%;;">
                  <el-option v-for="item in locatorOptions" :key="item.id" :label="item.name"
                    :value="item.id" />
                </el-select>
                <template>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="ml10">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-row>
          <el-col :span="24">
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span>盘点清单</span>
              </div>
              <el-table :data="form.items" border stripe max-height="320">
                <el-table-column type="index" width="55" align="center" />
                <el-table-column label="物品编号" align="center" prop="pno"></el-table-column>
                <el-table-column label="物品名称" align="center" prop="name"></el-table-column>
               <el-table-column label="库区" align="center" prop="areaName"></el-table-column>
               <el-table-column label="库位" align="center" prop="locatorName"> </el-table-column>
               <el-table-column label="账面数量" align="center" prop="books"></el-table-column>
               <el-table-column label="盘点数量" align="center" prop="nums">
                 <template slot-scope="scope">
                  <el-input v-model="scope.row.nums" placeholder="请输入盘点数量" @input="planChange($event,scope.row)"/>
                 </template>
               </el-table-column>
               <el-table-column label="盘点结果" align="center" prop="results">
                 <template slot-scope="scope" v-if="scope.row.nums">
                 {{scope.row.results }}
                 </template>
               </el-table-column>
              </el-table>
              <!-- <pagination small v-show="itemTotal>0" :total="itemTotal" :page.sync="formParams.pageNum" :limit.sync="formParams.pageSize"
                /> -->
            </el-card>
          </el-col>
        </el-row>
        <el-card>
          <div slot="header" class="clearfix">
            <span>数据统计</span>
          </div>
          <el-row :gutter="15">
            <el-col :span="8">
              <el-form-item label="账面数量" prop="books">
                <el-input v-model="form.books" placeholder="请输入账面数量" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="盘点数量" prop="nums">
                <el-input v-model="form.nums" placeholder="请输入盘点数量" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="盘点结果" prop="results">
                <el-input v-model="form.results" placeholder="请输入盘点结果" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="监盘人" prop="watcherId">
                <el-select v-model="form.watcherId" placeholder="请选择监盘人" style="width: 98%">
                  <el-option
                    v-for="item in userOptions"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="派单人" prop="dispatcherId">
                <el-select v-model="form.dispatcherId" placeholder="请选择派单人" style="width: 98%">
                  <el-option
                    v-for="item in userOptions"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="盘点人" prop="inventoryUser">
                <el-select v-model="form.inventoryUser" placeholder="请选择盘点人" style="width: 100%">
                  <el-option
                    v-for="item in userOptions"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userName"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态">
                  <el-option v-for="dict in dict.type.wms_inventory_status" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计划盘点时间" prop="planTime">
                <el-date-picker :clearable="false" v-model="form.planTime" type="date" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" class="datepicker-content"
                                popper-class="datepickerPopperClass"
                  placeholder="请选择计划盘点时间" style="width: 96%;"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <!-- <el-row :gutter="15" style="margin-top: 15px;">
          <el-col :span="6">
            <el-form-item label="账面数量" prop="books">
              <el-input v-model="form.books" placeholder="请输入账面数量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点数量" prop="nums">
              <el-input v-model="form.nums" placeholder="请输入盘点数量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点结果" prop="results">
              <el-input v-model="form.results" placeholder="请输入盘点结果" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option v-for="dict in dict.type.wms_inventory_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      </el-main>
      <el-footer>
        <div class="footerDivClass">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="close()">取 消</el-button>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
  import {
    listInventoryPlan,
    getInventoryPlan,
    delInventoryPlan,
    addInventoryPlan,
    updateInventoryPlan,
    initBean,
    dtlList
  } from "@/api/wms/inventoryPlan";
  import {
    listStore,
    storeTreeselect
  } from "@/api/wms/store";
  import {
    treeselect
  } from "@/api/system/dept";
  import {listUser} from "@/api/system/user"
  import { listInventory } from "@/api/wms/inventory";
  import { listStoreArea} from '@/api/wms/storeArea';
  import {listCabinetGroup } from "@/api/wms/cabinetGroup";
  import {listCabinet } from "@/api/wms/cabinet";
  import {listLocator } from "@/api/wms/locator";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "InventoryPlan",
    dicts: ['wms_inventory_status', 'sys_del_flag','sys_check_status','wms_put_task_area'],
    components: {
      Treeselect
    },
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        id:undefined,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 盘点计划表格数据
        inventoryPlanList: [],
        storeOptions: [],
        inventoryTypeOptions: [
          {
            id: '0',
            label: '非暂存物品'
          },
          {
            id: '1',
            label: '暂存物品'
          }
        ],
        storeTree: [],
        storeName: undefined,
        deptOptions: [],
        userOptions:[],
        userFormOptions:[],
        inventory:[],

        storeAreaOptions:[],
        cabinetGroupOptions:[],
        cabinetOptions:[],
        locatorOptions:[],

        items:[],
        clicks:0,
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          inventoryNo: undefined,
          storeId: undefined,
          inventoryUser: undefined,
          operator: undefined,
          operateTime: undefined,
          checker: undefined,
          checkStatus: undefined,
          checkTime: undefined,
          status: undefined,
          deptId: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined
        },
        itemTotal: 0,
        formParams: {
          pageNum: 1,
          pageSize: 10,
          storeId: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          inventoryNo: [{
            required: true,
            message: "单号不能为空",
            trigger: "blur"
          }],
          storeId: [{
            required: true,
            message: "仓库不能为空",
            trigger: "blur"
          }],
          inventoryType: [{
            required: true,
            message: "物品类型不能为空",
            trigger: "blur"
          }],
          watcherId: [{
            required: true,
            message: "监盘人不能为空",
            trigger: "blur"
          }],
          dispatcherId: [{
            required: true,
            message: "派单人不能为空",
            trigger: "blur"
          }],
          inventoryUser: [{
            required: true,
            message: "盘点人不能为空",
            trigger: "blur"
          }],
          deptId: [{
            required: true,
            message: "部门id不能为空",
            trigger: "blur"
          }],
        },
         ano:undefined,
         span:4,

         floorsOptions:[
           {name:'1层',value:'1'},
           {name:'2层',value:'2'},
           {name:'3层',value:'3'},
           {name:'4层',value:'4'},
           {name:'5层',value:'5'},
           {name:'6层',value:'6'},
           {name:'7层',value:'7'},
           {name:'8层',value:'8'}

         ]
      };
    },
    watch: {
      'form.storeId': {
        handler(newVal, oldVal) {
          this.getStoreArea(newVal);
          // this.initData()
        },
        // deep: true,
        immediate: true
      },
      'form.inventoryType': {
        handler(newVal, oldVal) {

        },
        // deep: true,
        immediate: true
      },
      'form.areaId':{
        handler(newVal){
          if(newVal){
            this.storeAreaOptions.forEach(item=>{
               if(item.id == newVal){
                 let ano = item.ano;
                 this.ano = ano;
                 if(ano == 'ZX'||ano == 'DX'){
                   this.queryParams.cabinetGroupId = undefined;
                 }else{
                   this.getCabinetGroup(newVal)
                   // this.initData()
                 }
               }
            })
          }
        },
        // deep: true,
        // immediate: true

      },
      'form.cabinetGroupId': {
        handler(newVal, oldVal) {
          if(newVal){
            this.getCabinet(newVal);
            // this.initData()
            if(this.ano == 'CL'){
              this.getLocator();
            }
          }
        },
        // deep: true,
        // immediate: true
      },
      'form.cabinetId': {
        handler(newVal, oldVal) {
          if(newVal){
            this.getLocator(newVal);
            // this.initData()
          }
        },
        // deep: true,
        // immediate: true
      },
      'form.floors': {
        handler(newVal, oldVal) {
          if(newVal){
            this.getLocator();
            // this.initData()
          }
        },
        // deep: true,
        // immediate: true
      },
      // 'form.locatorIds': {
      //   handler(newVal, oldVal) {
      //     console.info('newVal===>',newVal)
      //     if(newVal && newVal.length > 0){
      //       this.initData()
      //     }
      //   },
      //   // deep: true,
      //   immediate: true
      // },
    },
    created() {
      this.getStoreTreeselect();
      this.getTreeselect();
      this.getUsers();
      // this.form.storeId = this.$route.query.storeId;
      // this.form.deptId = this.$route.query.deptId
      this.form.id = this.$router.currentRoute.params.id;
      this.initData()
    },
    methods: {
      initData(){
        initBean(this.form).then((response) => {
          this.form = response.data;
          this.form.locatorIds = response.data.locators ? response.data.locators.split(','):[];
        });
      },
      getDtlList(){
        let params = {
          storeId:this.form.storeId,
          inventoryType:this.form.inventoryType,
          areaId:this.form.areaId,
          cabinetGroupId:this.form.cabinetGroupId,
          cabinetId:this.form.cabinetId,
          regions:this.form.regions,
          floors:this.form.floors,
          locatorIds:this.form.locatorIds,
          delFlag:this.form.delFlag
          }
        params.params = {};
        if (null != this.form.inTime && '' != this.form.inTime) {
          params.params["beginIntime"] = this.form.inTime[0];
          params.params["endIntime"] = this.form.inTime[1];
        }
        if(params.region === 'QB'){
          params.region = ''
        }

        dtlList(params).then((response) => {
          this.form.books=response.data.books;
          this.form.nums=response.data.nums;
          this.form.results=response.data.results;
          this.form.status=response.data.status;
          this.form.items = response.data.items;
        });
      },
      storeChange(e){
        console.info("storeChange",e);
      },
      /** 查询分类下拉树结构 */
      getStoreTreeselect() {
        storeTreeselect().then(response => {
          this.storeOptions = response.data;
        });
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      /** 查询库区*/
      getStoreArea(storeId){
        listStoreArea({storeId:storeId}).then(response=>{
          this.storeAreaOptions = response.rows;
        })
      },
      /** 查询智能柜信息 */
      getCabinetGroup(areaId){
        listCabinetGroup({areaId:areaId}).then(response=>{
          this.cabinetGroupOptions = response.rows;
        })
      },
      /** 查询智能柜信息 */
      getCabinet(cabinetGroupId){
        listCabinet({groupId:cabinetGroupId}).then(response=>{
          this.cabinetOptions = response.rows;
        })
      },
      getLocator(cabinetId){
        let floors = undefined;
        if(this.ano == 'PT'){
          floors = this.form.floors;
        }
        listLocator({cabinetGroupId:this.form.cabinetGroupId,cabinetId:cabinetId,floors:floors}).then(response=>{
          this.locatorOptions = response.rows;
        })
      },
      /** 搜索按钮操作 */
      handleQuery() {
        // this.queryParams.pageNum = 1;
        this.getDtlList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.form.areaId = undefined;
        this.form.cabinetGroupId = undefined;
        this.form.cabinetId = undefined;
        this.form.floors = undefined;
        this.form.locatorIds = undefined;
        this.handleQuery();
      },
      deptChange() {
        this.getUsers();
      },
      getUsers(){
        console.info("getUsers::")
        listUser({'userType':'sys_user','deptId':this.queryParams.deptId,'postCode':'Picker,PutTasker,Supervisor,Dispatcher'}).then(response => {
          this.userOptions = response.rows
        })
      },
      getFormUsers(){
        listUser({'userType':'sys_user','deptId':this.form.deptId}).then(response => {
          this.userFormOptions = response.rows
        })
      },
      selectDeptId() {
        this.getFormUsers();
      },
      planChange(e,row){
        let nums = e;
        let books = row.books;
        row.results = nums - books;
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      // handleNodeClick(data) {
      //   this.queryParams.storeId = data.id;
      //   this.handleQuery();
      // },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      /** 关闭按钮 */
      close() {
        const obj = {
          path: "/wms/wmsinventoryplan/inventoryPlan",
          query: { t: Date.now(), pageNum: this.$route.query.pageNum },
        };
        this.$tab.closeOpenPage(obj);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          inventoryNo: undefined,
          storeId: undefined,
          inventoryType:undefined,
          inventoryUser: undefined,
          operator: undefined,
          operateTime: undefined,
          checker: undefined,
          checkStatus: "0",
          checkTime: undefined,
          checkMemo: undefined,
          status: '0',
          remark: undefined,
          deptId: undefined,
          books: undefined,
          nums: undefined,
          results: undefined,
          pics: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined,
          items:[]
        };
        this.resetForm("form");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加盘点计划";
        this.form.storeId = this.queryParams.storeId
        this.form.deptId = this.queryParams.deptId
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateInventoryPlan(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.close();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addInventoryPlan(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
               this.close();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
.datepickerPopperClass{
  .el-button--text{
    display: none;
  }

  .el-time-spinner__wrapper{
    width: 100%;
  }

  .el-scrollbar:nth-child(2){
    display: none;
  }
}
.mainDiv {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.main_container {
  width: 100%;
  height: 100%;
}
.el-card {
  margin-bottom: 5px;
}
.el-footer {
  background-color: #ffffff;
  color: #333;
  text-align: right;
  line-height: 60px;
  border-top: 1px solid #e6ebf5;
  box-shadow: 0px 0px 10px #cdcdcd;
  z-index: 1000;
}
.footer-class {
  text-align: right;
  margin-top: 15px;
}
//顶部距离css
.topItem {
  margin-bottom: 0px;
}
</style>
